import Vue from 'vue'
import { isLogin } from './util';
import {API_URL} from './env.js'

/**
 * @param {String} url
 * @param {String} method
 * @param {Object} data 默认给{}
 */
export const request = ({ url, method, data }) => {
	console.log('data==',data)
	const token = wx.getStorageSync('token');
	if(typeof data == 'object'){
		console.log('in nin')
		data.TT_TOKEN = token;
		data.sourcefrom = 'wx';
		for(let key in data){
			if(data[key] == null || data[key] == 'null'){
				data[key] = ''
			}
		}
	} else if(typeof data == 'string'){
		data += `&TT_TOKEN=${token}&sourcefrom=wx`
	}
	
	return new Promise((resolve, reject)=> {
		uni.request({
			url: API_URL + url,
			method: method || 'POST',
			data: data || {},
			header: {
			    'content-type': 'application/x-www-form-urlencoded'
			 },
			success: (res) => {
				resolve(res);
				//token无效
				if(res.data.code === '203001'){
					console.log('登录失效')
					wx.removeStorageSync('token');
					uni.redirectTo({
						url:'/pages/login/login'
					})
				}
			},
			fail: (err) => {
				// uni.showToast({
				// 	title: '请求接口失败',
				// 	icon: 'none'
				// })
				reject(err);
			}
		});
	})
}